<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Upload } from '@element-plus/icons-vue';
import { uploadFile } from '@/api/file';
import { feedbackForm, feedbackFormTypes } from '@/api/file';

const feedbackTypes = ref([]);
onMounted(async () => {
    const res = await feedbackFormTypes();
    feedbackTypes.value = res.data;
})

const form = ref({
    name: '',
    wechat: '',
    company: '',
    position: '',
    feedback: '',
    fileId: '',
    feedbackTypes: []
});

const fileList = ref([]);
const fileUrl = ref(null);
const formRef = ref(null);

// 表单校验规则
const rules = reactive({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    wechat: [
        { required: true, message: '请输入微信号', trigger: 'blur' }
    ],
    feedback: [
        { required: true, message: '请输入反馈建议', trigger: 'blur' }
    ],
    feedbackTypes: [
        { required: true, message: '请选择反馈类型', trigger: 'change' }
    ]
});

/** 覆盖默认上传行为 */
function requestUpload() {
}

/** 上传预处理 */
const beforeUpload = (file) => {
    // 检查文件类型
    if (file && file.type.indexOf("image/") == -1) {
        return false;
    }
    
    // 检查文件大小（限制为2MB）
    const maxSize = 2 * 1024 * 1024; // 2MB
    if (file.size > maxSize) {
        ElNotification({
            title: 'Error',
            message: '文件大小不能超过2MB',
            type: 'error',
        })
        return false;
    }
    fileList.value = file;
    fileUrl.value = URL.createObjectURL(file);
    // 不再立即上传文件，而是在表单提交时上传
    return true;
}

/** 提交表单 */
const submitForm = () => {
    if (!formRef.value) return;
    
    formRef.value.validate((valid) => {
        if (valid) {
            // 使用FormData提交表单
            const formData = new FormData();
            formData.append("name", form.value.name);
            formData.append("wechat", form.value.wechat);
            formData.append("company", form.value.company);
            formData.append("position", form.value.position);
            formData.append("feedback", form.value.feedback);
            
            // 添加反馈类型
            formData.append("feedbackTypes", form.value.feedbackTypes);
            
            // 如果有文件，直接添加到formData中
            if (fileUrl.value) {
                formData.append("file", fileList.value);
            }

            // 提交表单
            feedbackForm(formData).then(res => {
                if (res.suc) {
                    ElNotification({
                        title: '提示',
                        message: '提交成功',
                        type: 'success',
                    })
                    // 重置表单
                    form.value = {
                        name: '',
                        wechat: '',
                        company: '',
                        position: '',
                        feedback: '',
                        fileId: '',
                        feedbackTypes: []
                    };
                    fileList.value = [];
                    fileUrl.value = null;
                    formRef.value.resetFields();
                } else {
                    ElNotification({
                        title: '提示',
                        message: '提交失败，请稍后重试',
                        type: 'error',
                    })
                }
            });
        } else {
            return false;
        }
    });
}
</script>

<template>
    <div class="custom-form-box">
        <div class="form-title">
            中国企业的全球化刚刚拉开序章，出海有很多迷雾和暗礁。贸行四海导航站自身也有很多错漏和不足之处，希望您对我们多指正，多建议。我们将对您的反馈，在1-2个工作日内进行响应。非常感谢您对贸行四海的帮助。</div>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入您的姓名" />
            </el-form-item>

            <el-form-item label="微信号" prop="wechat">
                <el-input v-model="form.wechat" placeholder="请输入您的微信号" />
            </el-form-item>

            <el-form-item label="公司名" prop="company">
                <el-input v-model="form.company" placeholder="请输入您的公司名称" />
            </el-form-item>

            <el-form-item label="职位" prop="position">
                <el-input v-model="form.position" placeholder="请输入您的职位" />
            </el-form-item>

            <el-form-item label="反馈类型" prop="feedbackTypes">
                <el-checkbox-group v-model="form.feedbackTypes">
                    <el-checkbox v-for="item in feedbackTypes" :key="item.value" :label="item.value">
                        {{ item.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item label="反馈建议" prop="feedback">
                <el-input v-model="form.feedback" type="textarea" :rows="4" placeholder="请输入您的反馈建议" />
            </el-form-item>

            <el-form-item label="附件" prop="file">
                <el-upload class="upload-demo" action="#" :http-request="requestUpload" :show-file-list="false"
                    :before-upload="beforeUpload">
                    <div v-if="fileUrl" class="upload-preview">
                        <img :src="fileUrl" class="upload-img" />
                        <div class="upload-actions">
                            <el-button type="primary" size="small">更换文件</el-button>
                        </div>
                    </div>
                    <div v-else class="upload-placeholder">
                        <el-icon class="upload-icon">
                            <Upload />
                        </el-icon>
                        <div class="upload-text">点击上传附件</div>
                        <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
                    </div>
                </el-upload>
                <div class="el-form-item__error" v-if="fileList.length > 0 && fileList[0].size > 2 * 1024 * 1024">
                    文件大小不能超过2MB
                </div>
                <div class="el-form-item__error" v-if="fileList.length > 0 && fileList[0].type.indexOf('image/') === -1">
                    文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm">提交反馈</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped>
::v-deep .el-form-item__label {
    color: #333;
}

.custom-form-box {
    padding:0 20px;
    background: white;
    border-radius: 8px;
    height: max-content;
    position: relative;
    margin: 0px auto auto;
    display: flex;
    flex-direction: column;
    transition: all .3s linear;
}

.form-title {
    text-align: left;
    margin-bottom: 30px;
    text-indent: 20px;
    color: #333;
    font-size: 18px;
}

.upload-demo {
    width: 100%;
}

.upload-placeholder {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    padding: 20px;
    text-align: center;
}

.upload-placeholder:hover {
    border-color: #409EFF;
}

.upload-icon {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 10px;
}

.upload-text {
    color: #606266;
    font-size: 14px;
    margin-bottom: 5px;
}

.upload-tip {
    color: #909399;
    font-size: 12px;
}

.upload-preview {
    position: relative;
    width: 100%;
    text-align: center;
}

.upload-img {
    width: 100%;
    max-height: 200px;
    object-fit: contain;
}

.upload-actions {
    margin-top: 10px;
}
</style>